import React, { useEffect, useState } from 'react'
import http from '../../api'
import { useNavigate } from 'react-router-dom'
import style from './index.module.css'
import computedHeight, { computedLoveHeight } from '../../utils'
import AttentionList from '../../components/Mine/AttentionList'
import CircleLoveList from '../../components/Mine/CircleLoveList'
import { Toast } from 'antd-mobile'
import { CircleList, CircleLove, CircleLoveResult, SaveSelect, UserInfoResult, UserStaticType } from '../../myTypes'
import Loading from '../../components/publicComponents/Loading'

export default function Mine() {
  let [userId, setUserId] = useState('')
  const navigate = useNavigate()
  const [curType, setCurType] = useState<'喜欢' | '圈子' | '关注'>('圈子')
  const [userInfo, setUserinfo] = useState<UserInfoResult>()
  const [userDesc, setUserDesc] = useState('')
  const [useStatic, setUserStatic] = useState<UserStaticType>()
  const [isEdit, setEdit] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  let [leftSelect, setLeftSelect] = useState<Array<SaveSelect>>([])
  let [rightSelect, setRightSelect] = useState<Array<SaveSelect>>([])
  let [leftLoveList, setLeftLoveList] = useState<Array<CircleLove>>([])
  let [rightLoveList, setRightLoveList] = useState<Array<CircleLove>>([])
  let [page, setPage] = useState(1)

  useEffect(() => {
    const id = localStorage.getItem('userId')
    if (id) {
      userId = id
      sendRequestUserInfo()
      SendRequestUserFans()
      setUserId(id)
    } else {
      navigate('/login')
    }
  }, [])
  async function sendRequestUserInfo() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await http('get', '/mty/my/info', {
      accountId: userId
    })
    Toast.clear()
    if (data) {
      const userInfo = data.data as UserInfoResult
      setUserDesc(userInfo.signature)
      setUserinfo(userInfo)
    }
  }

  async function SendRequestUserFans() {
    const data = await http('get', '/mty/circle/statistic', {
      userId: userId
    })
    if (data) {
      const userStatic = data.data as UserStaticType
      setUserStatic(userStatic)
    }
  }

  function SendRequestGetCircles() {
    // 圈子
    return http('get', '/mty/my/getCircles', {
      pageNum: page,
      pageSize: 10,
      userId: userId,
      accountId: userId
    })
  }

  function SendRequestGetCircleLove() {
    // 喜欢
    return http('get', '/mty/circleLove/get', {
      pageNum: page,
      pageSize: 10,
      userId: userId,
      accountId: userId
    })
  }
  function SendRequestGetAttentionCircles() {
    // 关注
    return http('get', '/mty/my/getAttentionCircles', {
      pageNum: page,
      pageSize: 10,
      userId: userId,
      accountId: userId
    })
  }

  async function updateSignature() {
    setEdit(false)
    const data = await http('post', '/mty/my/updateSignature', {
      userId,
      signature: userDesc
    })
    if (data && data.code === 200) {
      Toast.show({
        content: '修改成功'
      })
      sendRequestUserInfo()
    }
  }

  function toggleType(type: '关注' | '圈子' | '喜欢') {
    if (type === curType) return
    leftLoveList = []
    leftSelect = []
    rightLoveList = []
    rightSelect = []
    page = 1
    switch (type) {
      case '圈子':
        SendRequestGetCircles()
        break
      case '喜欢':
        loadMoreLove()
        break
      case '关注':
        loadMoreAttention()
        break
    }
    setPage(1)
    setCurType(type)
    setLeftSelect(rightSelect)
    setRightSelect(leftSelect)
    setLeftLoveList(leftLoveList)
    setRightLoveList(rightLoveList)
  }

  // 加载更多
  async function loadMoreAttention() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await SendRequestGetAttentionCircles()
    if (data) {
      const circleData = data.data as CircleList
      setPage((prePage) => prePage + 1)
      setHasMore(() => circleData.list.length > 0)
      // 调用工具类中的方法保存数据
      computedHeight(circleData.list, setLeftSelect, setRightSelect)
    }
    Toast.clear()
  }
  // 加载更多
  async function loadMoreLove() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await SendRequestGetCircleLove()
    if (data) {
      const loveList = data.data as CircleLoveResult
      setPage((prePage) => prePage + 1)
      setHasMore(() => loveList.list.length > 0)
      computedLoveHeight(loveList.list, setLeftLoveList, setRightLoveList)
    }
    Toast.clear()
  }
  return (
    <div>
      <div className={style['user-container']}>
        <div className={style['mine-nav']}>
          个人中心
          <div
            className={style['setting-icon']}
            onClick={() => {
              navigate('/setting')
            }}
          >
            <img src="/static/user/icon-setUp-505.png" alt="" />
          </div>
        </div>
        {/* 用户账号信息 */}
        <div className={style['user-account']}>
          <div className={style['user-head-img']}>
            <img src={userInfo?.headImg} alt="" />
          </div>
          <div className={style.account}>
            <div className={style['nickname']}>
              <span className={style.text}>{userInfo?.nickName}</span>
              <span className={style['member']}>会员1级</span>
            </div>
            <div className={style['account-number']}>牧童游号:{userInfo?.id}</div>
          </div>
        </div>
      </div>
      {/* 用户描述 */}
      <div className={style['user-desc']}>
        {!isEdit && (
          <div className={style['user-desc-finish']}>
            <div className={style['desc-text']}>{userInfo?.signature}</div>
            <div className={style['edit-container']}>
              <div className={style['edit-icon']}>
                <img src="/static/user/icon-edit-9e9.png" alt="" />
              </div>
              <div className={style.edit} onClick={() => setEdit(true)}>
                编辑
              </div>
            </div>
          </div>
        )}

        {isEdit && (
          <div className={style['user-desc-edit']}>
            <div className={style['desc-input']}>
              <input type="text" value={userDesc} onInput={(e: any) => setUserDesc(e.target.value)} />
            </div>
            <div className={style['edit-container']}>
              <div className={style['edit-icon']}>
                <img src="/static/user/icon-edit-9e9.png" alt="" />
              </div>
              <div className={style.edit} onClick={updateSignature}>
                完成
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 用户性别 */}
      <div className={style['gender']}>
        <div className={style['user-gender']}>
          <div className={style['gender-icon']}>
            <img src="/static/user/icon-sex-male.png" alt="" />
          </div>
          <div className={style['gender-text']}>{userInfo?.sex || '男'}</div>
        </div>
      </div>

      {/* 用户获赞粉丝关注 */}
      <div className={style['fans-container']}>
        <div className={style['fans-item']}>
          <div className={style['fans-text']}>获赞</div>
          <div className={style['fans-number']}>{useStatic?.love}</div>
        </div>
        <div className={style['fans-item']}>
          <div className={style['fans-text']}>粉丝</div>
          <div className={style['fans-number']}>{useStatic?.fans}</div>
        </div>
        <div className={style['fans-item']}>
          <div className={style['fans-text']}>关注</div>
          <div className={style['fans-number']}>{useStatic?.attention}</div>
        </div>
      </div>

      {/* 用户订单评价收藏牛气卡包 */}
      <div className={style['order-list']}>
        <div className={style['order-item']}>
          <div className={style['order-icon']}>
            <img src="/static/user/icon-mine-order.png" alt="" />
          </div>
          <div>订单</div>
        </div>
        <div className={style['order-item']}>
          <div className={style['order-icon']}>
            <img src="/static/user/icon-mine-evaluate.png" alt="" />
          </div>
          <div>评价</div>
        </div>
        <div className={style['order-item']}>
          <div className={style['order-icon']}>
            <img src="/static/user/icon-mine-collect.png" alt="" />
          </div>
          <div>收藏</div>
        </div>
        <div className={style['order-item']}>
          <div className={style['order-icon']}>
            <img src="/static/user/icon-mine-integral.png" alt="" />
          </div>
          <div>牛气</div>
        </div>
        <div className={style['order-item']}>
          <div className={style['order-icon']}>
            <img src="/static/user/icon-mine-cardBag.png" alt="" />
          </div>
          <div>卡包</div>
        </div>
      </div>

      {/* 用户圈子喜欢关注 */}
      <div className={style['user-circle-container']}>
        <div className={`${style['circle-item']} ${curType === '圈子' && style.active}`} onClick={() => toggleType('圈子')}>
          圈子
          <span>{useStatic?.circle}</span>
        </div>
        <div className={`${style['circle-item']} ${curType === '喜欢' && style.active}`} onClick={() => toggleType('喜欢')}>
          喜欢
          <span>{useStatic?.circleLove}</span>
        </div>
        <div className={`${style['circle-item']} ${curType === '关注' && style.active}`} onClick={() => toggleType('关注')}>
          关注
          <span>{useStatic?.circleAttention}</span>
        </div>
      </div>
      {/* 数据展示 */}
      <div className={style['show-data']}>
        {/* 圈子数据展示 */}
        {curType === '圈子' && <div className={style.empty}>暂无相关的圈子</div>}
        {curType === '关注' && leftSelect.length === 0 && rightSelect.length === 0 && <div className={style.empty}>暂无相关的圈子</div>}
        {curType === '喜欢' && leftLoveList.length === 0 && rightLoveList.length === 0 && <div className={style.empty}>暂无相关的圈子</div>}
        {/* 喜欢数据展示 */}

        {curType === '喜欢' && <CircleLoveList style={style} leftSelect={leftLoveList} rightSelect={rightLoveList} />}

        {/* 关注数据展示 */}
        {curType === '关注' && <AttentionList style={style} leftSelect={leftSelect} rightSelect={rightSelect} />}
      </div>
      {curType === '关注' && (
        <div className={style['load-more']}>
          {hasMore ? (
            <span className={style['load-more-btn']} onClick={loadMoreAttention}>
              加载更多
            </span>
          ) : (
            <span>没有更多了...</span>
          )}
        </div>
      )}
      {curType === '喜欢' && (
        <div className={style['load-more']}>
          {hasMore ? (
            <span className={style['load-more-btn']} onClick={loadMoreLove}>
              加载更多
            </span>
          ) : (
            <span>没有更多了...</span>
          )}
        </div>
      )}
    </div>
  )
}
